import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Layout from '../components/layout/Layout.vue'
import Home from '../views/Home.vue'
import UserList from '../views/user/UserList.vue'
import HelpAbout from '../views/help/HelpAbout.vue'
import BlogList from '../views/blog/BlogList.vue'
import BlogTypesList from '../views/blog/BlogTypesList.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/login', name: 'Login', component: Login },
  { path: '/', name: 'Layout', component: Layout, redirect: '/home',
    children: [
      { path: '/home', name: 'Home', component: Home, meta: { title: '首页', icon: 'el-icon-s-home' } },
      { path: '/user/list', name: 'UserList', component: UserList, meta: { title: '用户列表', icon: 'el-icon-user' }},
      { path: '/help/about', name: 'HelpAbout', meta: { title: '关于', icon: 'el-icon-question' }, component: HelpAbout },
      { path: '/blog/list', name: 'BlogList', meta: { title: '博客列表', icon: 'el-icon-question' }, component: BlogList },
      { path: '/blog/typesList', name: 'BlogTypesList', meta: { title: '博客类型列表', icon: 'el-icon-question' }, component: BlogTypesList },
    ]
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断是否有token
  const token = localStorage.getItem('token')
  // 如果访问的是登录页，直接放行
  if (to.path === '/login') {
    next()
  } else {
    // 如果没有token，重定向到登录页
    if (!token) {
      next('/login')
    } else {
      next()
    }
  }
})

export default router
